import React, { Component } from 'react'
import gradeApi from '../../../api/grade/index'
import { getCourseListApi, getCourseDetailsApi, courseUpdateApi, courseUploadApi } from '../../../api/course/course'
import { subject, teacher } from '../../../api/index'
import { Table, Button, Image, Modal, Form, Input, Upload, Select, DatePicker, Space } from 'antd';
import { connect } from 'dva'
const { RangePicker } = DatePicker;



const { Option } = Select;
const layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
};
const tailLayout = {
    wrapperCol: { offset: 8, span: 16 },
};


class Course extends Component {
    state = {
        columns: [
            { title: '课程名称', dataIndex: 'name' },
            { title: '有效期', dataIndex: 'expiry' },
            {
                title: '是否精品', dataIndex: 'isFine', render: (data) => {
                    if (data === '1') {
                        return <span>精品</span>
                    }
                    return <span>普通</span>
                }
            },
            {
                title: '是否免费', dataIndex: 'isFree', render: (data) => {
                    if (data === '0') {
                        return <span>免费</span>
                    }
                    return <span>付费</span>
                }
            },
            { title: '课程价格', dataIndex: 'price' },
            { title: '发布时间', dataIndex: 'pubTime' },
            {
                title: '是否下架', dataIndex: 'status', render: (data) => {
                    if (data === 'y') {
                        return <span>正常</span>
                    }
                    return <span>下架</span>
                }
            },
            {
                title: '所属教师', dataIndex: 'teacherId', render: (data) => {
                    let item = this.state.teacherList
                    for (var i = 0; i < item.length; i++) {
                        if (data === item[i].id) {
                            return <span>{item[i].name}</span>
                        }
                    }
                }
            },
            {
                title: '所属科目', dataIndex: 'subjectId', render: (data) => {
                    let item = this.state.subjectList
                    for (var i = 0; i < item.length; i++) {
                        if (data === item[i].id) {
                            return <span>{item[i].name}</span>
                        }
                    }
                }
            },
            {
                title: '所属年级', dataIndex: 'gradeId', render: (data) => {
                    let item = this.state.gradeList
                    for (var i = 0; i < item.length; i++) {
                        if (data === item[i].id) {
                            return <span>{item[i].name}</span>
                        }
                    }
                }
            },
            { title: '观看数', dataIndex: 'viewNum' },
            {
                title: '封面',
                dataIndex: 'cover',
                key: 'y',
                render: (data) => {
                    // console.log(2342, data);
                    return <Image
                        width={50}
                        src={'http://192.168.41.80:8090/k15/cover/' + data}
                    />
                },
            },
            {
                title: '操作',
                key: 'x',
                render: (data) => {
                    // console.log(222, data);
                    return <><Button type='primary' size='middle' onClick={() => this.changeCourse(data)}>修改</Button>
                    &nbsp;
                        <Button type='primary' size='middle' onClick={() => this.gotoLession(data)}>查看课时</Button>
                    </>
                },
            },
        ],

        data: [
            {
                key: 1,
                name: 'John Brown',
                age: 32,
                address: 'New York No. 1 Lake Park',
                description: 'My name is John Brown, I am 32 years old, living in New York No. 1 Lake Park.',
            },
            {
                key: 2,
                name: 'Jim Green',
                age: 42,
                address: 'London No. 1 Lake Park',
                description: 'My name is Jim Green, I am 42 years old, living in London No. 1 Lake Park.',
            },
            {
                key: 3,
                name: '1123213',
                age: 29,
                address: 'Jiangsu No. 1 Lake Park',
                description: 'This not expandable',
            },
            {
                key: 4,
                name: 'Joe Black',
                age: 32,
                address: 'Sidney No. 1 Lake Park',
                description: 'My name is Joe Black, I am 32 years old, living in Sidney No. 1 Lake Park.',
            },
        ],
        course: [
            // { id: 1, name: '111', expiry: '231', isFine: '1', isFree: '1', price: 12, pubTime: '2020/1/1', status: 'fou', viewNum: 12, cover: '123', description: '1231231312313132' },
            // { id: 2, name: '111', expiry: '231', isFine: '1', isFree: '1', price: 12, pubTime: '2020/1/1', status: 'fou', viewNum: 12, cover: '123', description: 'wqeqweqeqeqw' }
        ],
        visible: false,
        loading: false,
        fileList: [],

        gradeList: [],
        subjectList: [],
        teacherList: [],
        imgUrl: '',
        pubTime: '',
        id: 1
    }

    gotoLession = (data) => {
        console.log(3434, data);
        this.props.history.push('/home/lesson?id=' + data.id)
    }

    // 模态框
    componentDidMount() {
        // this.props.dispatch({ type: 'courseList/getCourseList' })
        this.getMsg()
        this.getgrade()
        this.getsubject()
        this.getteacher()
    }
    getgrade = async () => {
        var { data } = await gradeApi.getGradeListApi()
        this.setState({ gradeList: data })
    }
    getsubject = async () => {
        var { data } = await subject.getSubjectList()
        this.setState({ subjectList: data })
    }
    getteacher = async () => {
        console.log(123);
        var { data } = await teacher.getTeacherListApi({})
        // console.log(123123, records);
        this.setState({ teacherList: data.records })
    }
    getMsg = async () => {
        var { data } = await getCourseListApi()
        this.setState({ course: data.records })



        // console.log(555, data2);
        // this.setState({ gradeList: data1, subjectList: data2, teacherList: data3.records })
        // const { account, imgUrl, userGroup } = await userMsgApi()
        // console.log(123, data.records);

        // const fileList1 = [{ uid: imgUrl, thumbUrl: 'http://jacklv.cn/images/' + imgUrl }]
        // this.setState({ fileList: fileList1 })
        // console.log(this.state.fileList);
        console.log(1212, this.ins);
        // this.ins.setFieldsValue({ account, userGroup, imgUrl: fileList1 })
    }
    // 时间选择
    onChange = (value, dateString) => {
        console.log('Selected Time: ', value);
        console.log('Formatted Selected Time: ', dateString);
        this.setState({ pubTime: dateString })
    }
    onFinish = async (values) => {
        console.log('Success:', values);
        values.isFine = '普通' ? '0' : '1'
        values.isFree = '免费' ? '0' : '1'
        values.status = '正常' ? 'y' : 'n'
        values.imgUrl = this.state.imgUrl
        values.pubTime = this.state.pubTime
        values.id = this.state.id
        console.log(44444, values);
        const data = await courseUpdateApi(values)
        console.log(5555, data);
    };

    onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };
    normFile = (e) => {
        console.log('Upload event:', e.file.name);
        this.setState({ imgUrl: e.file.name })

        if (Array.isArray(e)) {
            return e;
        }
        this.setState({ fileList: e.fileList })
        return e && e.fileList;
    };


    changeCourse = async (node) => {
        const { data } = await getCourseDetailsApi(node.id)
        console.log(7777, data);
        this.setState({ id: data.id })
        if (this.ins) {
            const fileList1 = [{ uid: data.cover, thumbUrl: 'http://192.168.41.80:8090/k15/cover/' + data.cover }]
            this.ins.setFieldsValue({
                ...data,
                isFine: data.isFine === '0' ? '普通' : '精品',
                isFree: data.isFree === '0' ? '免费' : '付费',
                status: data.status === 'y' ? '正常' : '下架',
                imgUrl: fileList1
            })

            this.setState({ fileList: fileList1 })
        }
        this.setState({
            visible: true
        })
    }
    changeVisible = () => {
        this.setState({
            visible: true
        })
    }
    close = (status) => {

        this.setState({
            visible: status
        })
    }
    handleChange = (value) => {
        console.log(`selected ${value}`);
    }
    render() {
        const { columns, data, course, visible, gradeList, subjectList, teacherList, fileList } = this.state
        return (
            < div >
                <Table
                    columns={columns}
                    dataSource={course}
                    rowKey='id'
                    expandable={{
                        expandedRowRender: record => <p key={record.id} style={{ margin: 0 }}>{record.description}</p>,
                        rowExpandable: record => {
                            // console.log(1111, record);
                            return record.name !== 'Not Expandable'
                        },
                    }}
                // dataSource={data}
                />
                <Modal
                    title="课程修改"
                    centered
                    visible={visible}
                    onOk={() => this.close(false)}
                    onCancel={() => this.close(false)}
                    width={1000}
                >
                    <Form
                        {...layout}
                        name="basic"
                        // initialValues={}
                        onFinish={this.onFinish}
                        onFinishFailed={this.onFinishFailed}
                        style={{ width: 800 }}
                        ref={ins => this.ins = ins}
                    >
                        <Form.Item
                            label="课程名称"
                            name='name'
                            rules={[{ required: true, message: '请输入课程名称!' }]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label="有效期"
                            name="expiry"
                            rules={[{ required: true, message: '请输入有效期!' }]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label="是否精品"
                            name="isFine"
                            rules={[{ required: true, message: '请选择是否是精品!' }]}
                        >
                            <Select style={{ width: '100%' }} onChange={this.handleChange}>
                                <Option value="0">普通</Option>
                                <Option value="1">精品</Option>
                            </Select>
                        </Form.Item>
                        <Form.Item
                            label="是否免费"
                            name="isFree"
                            rules={[{ required: true, message: '请选择是否免费!' }]}
                        >
                            <Select style={{ width: '100%' }} onChange={this.handleChange}>
                                <Option value="0">免费</Option>
                                <Option value="1">付费</Option>
                            </Select>
                        </Form.Item>
                        <Form.Item
                            label="课程价格"
                            name="price"
                            rules={[{ required: true, message: '请输入价格!' }]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label="课时数"
                            name="lessonNum"
                            rules={[{ required: true, message: '请输入正确数量!' }]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label="所属教师"
                            name="teacherId"
                            rules={[{ required: true, message: '请选择所属教师!' }]}
                        >
                            <Select style={{ width: '100%' }} onChange={this.handleChange}>
                                {
                                    teacherList.map(item => {
                                        return <Option key={item.id} value={item.id}>{item.name}</Option>
                                    })
                                }
                            </Select>
                        </Form.Item>
                        <Form.Item
                            label="所属科目"
                            name="subjectId"
                            rules={[{ required: true, message: '请选择所属科目!' }]}
                        >
                            <Select style={{ width: '100%' }} onChange={this.handleChange}>
                                {
                                    subjectList.map(item => {
                                        return <Option key={item.id} value={item.id}>{item.name}</Option>
                                    })
                                }
                            </Select>
                        </Form.Item>
                        <Form.Item
                            label="所属年级"
                            name="gradeId"
                            rules={[{ required: true, message: '请选择所属年级!' }]}
                        >
                            <Select style={{ width: '100%' }} onChange={this.handleChange}>
                                {
                                    gradeList.map(item => {
                                        return <Option key={item.id} value={item.id}>{item.name}</Option>
                                    })
                                }
                            </Select>
                        </Form.Item>
                        <Form.Item
                            label="是否下架"
                            name="status"
                            rules={[{ required: true, message: '请选择是否下架!' }]}
                        >
                            <Select style={{ width: '100%' }} onChange={this.handleChange}>
                                <Option value="y">正常</Option>
                                <Option value="n">下架</Option>
                            </Select>
                        </Form.Item>
                        {/* 发布时间 */}
                        <Form.Item
                            label="发布时间"
                            name="pubTime"
                        // rules={[{ required: true, message: '请选择发布时间!' }]}
                        >
                            <Space direction="vertical" size={12}>
                                <DatePicker showTime onChange={this.onChange} onOk={this.onOk} />
                            </Space>
                        </Form.Item>

                        <Form.Item
                            label="观看数"
                            name="viewNum"
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label="购买数"
                            name="buyNum"
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label="课程描述"
                            name="description"
                        >
                            <Input />
                        </Form.Item>


                        <Form.Item
                            name="imgUrl"
                            label="头像"
                            valuePropName="fileList"
                            getValueFromEvent={this.normFile}
                        >
                            <Upload name="avatar"
                                action="http://192.168.41.80:8080/admin/course/upload"
                                listType="picture-card"
                                // beforeUpload={async (file, fileList) => {
                                //     console.log(2020, file, fileList);
                                //     console.log(file.lastModified);
                                //     const fd = new FormData()
                                //     this.setState({ imgUrl: file.name })
                                //     fd.append('coverFile', file.lastModified)
                                //     // await courseUploadApi({ coverFile: file.lastModified })

                                // }}
                                headers={{ 'x-auth-token': localStorage.getItem('token') }}
                            >
                                {/* 上传 */}
                                {
                                    !fileList.length && '图片上传'
                                }

                            </Upload>
                        </Form.Item>

                        <Form.Item {...tailLayout}>
                            <Button type="primary" htmlType="submit">
                                提交
                            </Button>
                        </Form.Item>
                    </Form>
                </Modal>
            </div >
        )
    }
}
const mapStateToProps = (state) => {
    return {
        list: state.courseList.list
    }
}

export default connect(mapStateToProps)(Course)